from django.conf import settings
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.forms import AuthenticationForm
from django.http import HttpResponseRedirect as redirect
from django.contrib.auth import authenticate
from StartGroup.models import Group
from announcement.forms import AnnouncementForm
import StartGroup.Constants
import connectpeople.Constants
from announcement.models import Announcement
from  django.http import QueryDict
from utils import activity_module, common_query, common_methods
import simplejson
from django.http import HttpResponse
import threading

# render form for Announcement
def announcementFormView(request, group_web_address):
    group_web_addr = group_web_address
    group_info = getGroupInfo(group_web_addr)              
    
    # Obtain user id
    userid = request.session[connectpeople.Constants.session_userid]
    
    # Get User object with permissions assigned
    permission = common_query.get_user_group_permission(userid, group_web_addr, False)
    
    # Group Info form initialization
    announcement_form = AnnouncementForm()
    return render_to_response("announcement/announcementForm.html",
                      {'announcement_form': announcement_form,'group':group_info,
                       'permission':permission},
                      context_instance = RequestContext(request))
    

# Save the form
def announcementView(request, group_web_address):
    
    group_web_addr = group_web_address
    group = getGroupInfo(group_web_addr)
    userid = request.session[connectpeople.Constants.session_userid]
    
    # Save the Announcement    
    if request.method == 'POST':
        
        try:
            # Take the Action String to identif which action to perform
            action = request.POST.__getitem__('action')
        except:
            action = None        
        
        if action == "deleteAnnouncement":
            # Delete Announcement
            announce_id = request.POST.__getitem__('anid')
            Announcement.objects.get(id=announce_id).delete()
            response = simplejson.dumps({'success':'success'})
        else:
            # Save and insert new row in table
            # Announcement form initialization
            announcement_form = AnnouncementForm(data=request.POST)            
            if announcement_form.is_valid():
                announcement = announcement_form.save(userid, group)
                
                # Announcement Update Activity save
                activity_module.setActivityNode(announcement.title, userid, group_web_addr, connectpeople.Constants.new_announcement_action)
                
                # Get email ids of these users
                recipient_list = common_query.getGroupMembersEmailIds(group_web_addr, connectpeople.Constants.new_announcement_email_flag_constant)
                # Compose subject for the email
                subj = "New Announcement Posted"
                # Send Email alerts. Use threading to speed up things
                new_comment_thread= threading.Thread(target=common_methods.send_email_helper, kwargs={'a_sender':Announcement, 'a_email':recipient_list, 'a_model':announcement, 'a_subject':subj, 'a_template':"email/newAnnouncementEmail.html"})
                new_comment_thread.setDaemon(True)
                new_comment_thread.start()
            else:
                print "invalid"
                # Get User object with permissions assigned
                permission = common_query.get_user_group_permission(userid, group_web_addr, False)
    
                return render_to_response("announcement/announcementForm.html",
                      {'announcement_form': announcement_form,'group':group,
                       'permission':permission},
                      context_instance = RequestContext(request))                
    
    if request.is_ajax():
        return HttpResponse(response,
        content_type="application/javascript")
    
    # get all the group announcements
    announcements = Announcement.objects.filter(group= group_web_addr).order_by('-created_date')    
    
    # Get User object with permissions assigned
    permission = common_query.get_user_group_permission(userid, group_web_addr, False)
                    
    return render_to_response("announcement/announcementView.html",
                              {'announcements': announcements,'group':group, 'userid':userid, 'permission':permission},
                              context_instance = RequestContext(request))

# Helper function to obtain Group related to a group_web_address
def getGroupInfo(group_web_addr):
    return Group.objects.get(group_web_address= group_web_addr)